<template>
  <div class="common-layout">
    <el-row :gutter="24">
      <el-col :span="4" :offset="0">
        <div>
          <el-input v-model="filterText" class="fitler" placeholder="筛选">
            <template #prefix>
              <el-icon class="el-input__icon"><Search /></el-icon> </template
          ></el-input>
        </div>
        <div class="mt-2">
          <el-tree
            ref="hostGroupRef"
            :data="hostStore.hostTree"
            :props="hostDefaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            default-expand-all
            @node-click="handleNodeClick"
            @node-contextmenu="rightClick"
          />
          <div class="rightMenu" v-show="showRightMenu">
            <ul>
              <li @click="addMenu">
                <el-button type="primary" link>新增分组</el-button>
              </li>
              <li @click="addSonMenu">
                <el-button type="primary" link>编辑分组</el-button>
              </li>
              <li @click="delMenu">
                <el-button type="primary" link>删除分组</el-button>
              </li>
            </ul>
          </div>
        </div>
      </el-col>
      <el-col :span="20" :offset="0">
        <div>
          <el-tabs
            v-model="editableTabsValue"
            type="card"
            editable
            class="demo-tabs"
            @tab-remove="removeTab"
            @tab-change="changeTab"
            style="min-width: 100px"
          >
            <el-tab-pane
              v-for="item in editableTabs"
              :key="item.name"
              :label="item.name"
              :name="item.uuid"
            >
            </el-tab-pane>
          </el-tabs>
        </div>

        <div style="height: 750px">
          <pre class="luban-pre" v-if="!editableTabs.length">
          {{ app.logo }}
        </pre
          >
          <div
            class="web-terminal"
            v-for="item in hostList"
            v-show="item.uuid == editableTabsValue"
          >
            <div :id="item.selector"></div>
          </div>
        </div>
        <div class="mt-3"></div>
        <el-row :gutter="20">
          <el-col :span="18" :offset="0">
            <el-input
              v-model="msg"
              placeholder="输入命令发送至全部终端"
            ></el-input
          ></el-col>
          <el-col :span="2" :offset="0">
            <el-button @click="sendAllTerm" type="primary"
              >发送</el-button
            ></el-col
          >
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { onDeactivated, ref, watch, onMounted } from "vue";
import useWebShell from "~/pinia/cmdb/host/webshell.js";
import useHost from "~/pinia/cmdb/host/host.js";
import { useApp } from "~/pinia/app.js";
import { useRoute } from "vue-router";
import GetUUID from "~/utils/uuid.js";
import { message } from "../../utils/utils";

// el tree 右键自定义菜单

const showRightMenu = ref(false);
const rightClick = (event, data, node, json) => {
  console.log(data, node, json);
  showRightMenu.value = false;
  let menu = document.querySelector(".rightMenu");
  menu.style.left = event.clientX + "px";
  menu.style.top = event.clientY + "px";
  showRightMenu.value = true;
  document.addEventListener("click", show);
};
const show = () => {
  showRightMenu.value = false;
};
const addGroup = () => {};

// html 元素主机列表
const hostList = ref([]);

// 用于获取app.logo
const app = useApp();
// 用于获取路由参数
const route = useRoute();

const webshellStore = useWebShell();
const instanceID = ref("");

// 顶部tab标签相关
const editableTabsValue = ref("");
const editableTabs = ref([]);

// 发送命令相关
const msg = ref("");
const sendAllTerm = () => {
  webshellStore.SendAllTerm(msg.value);
};

const removeTab = (targetKey) => {
  let lastIndex = 0;
  editableTabs.value.forEach((item, i) => {
    if (item.uuid === targetKey) {
      lastIndex = i - 1;
      webshellStore.CloseByInstanceID(item.instanceID);
      if (lastIndex === -1) {
        editableTabs.value = [];
        editableTabsValue.value = "";
        instanceID.value = "";
      }
    }
  });
  editableTabs.value = editableTabs.value.filter(
    (tab) => tab.uuid != targetKey
  );
};

const changeTab = (insID) => {
  editableTabsValue.value = insID;
  webshellStore.SetForcus(insID);
};

// 筛选相关
const hostGroupRef = ref(null);
const filterText = ref("");
const filterNode = (value, data) => {
  if (!value) return true;
  return data.description.indexOf(value) !== -1;
};
watch(filterText, (val) => {
  hostGroupRef.value.filter(val);
});

// 点击触发事件
const handleNodeClick = (row) => {
  //  为什么要使用uuid？
  // 需要保证每个标签的name不能重复

  const uuid = GetUUID();

  // 避免点击目录
  if (row.instanceID === undefined) {
    return;
  }
  // 生成一个唯一id
  const onlyID = `xterm-${row.instanceID}-${uuid}`;

  hostList.value.push({
    uuid: uuid,
    selector: onlyID,
  });

  editableTabs.value.push({
    uuid: uuid,
    selector: onlyID,
    instanceID: row.instanceID,
    name: `${row.name}-${row.address}`,
  });
  editableTabsValue.value = uuid;

  // 需要等待页面元素加载完成后再调用，否则会获取不到dom
  setTimeout(() => {
    webshellStore.setTermID(onlyID);
    webshellStore.initTerm(row.instanceID);
    webshellStore.initSocket(row.instanceID);
  }, 1000);
};

// fromOnlyID 用于保存从主机页面点击终端跳转后生成的onlyID
const fromOnlyID = ref("");
// init 仅用于初始化 从主机页面点击终端跳转后 生成html元素 并插入顶部标签
const init = () => {
  const temp = route.query.instanceID;
  const name = route.query.name;
  if (temp != undefined && name != undefined) {
    const uuid = GetUUID();
    const onlyID = `xterm-${temp}-${uuid}`;

    instanceID.value = temp;
    fromOnlyID.value = onlyID;

    // 向html列表中添加元素
    hostList.value.push({
      uuid: uuid,
      selector: onlyID,
    });

    // 向标签页中添加元素
    editableTabs.value.push({
      uuid: uuid,
      selector: onlyID,
      instanceID: instanceID.value,
      name: name,
    });

    // 设置当前选中标签
    editableTabsValue.value = uuid;
  }
};

init();
const hostStore = useHost();
hostStore.initHostTree();

// 仅用于从主机界面点击终端跳转 初始化xterm与websocket,判断是否有权限
onMounted(() => {
  window.addEventListener("resize", webshellStore.fitListener);

  // 如果顶部标签为空并且主机列表为空,则判断改用户没有任何主机
  if (!editableTabs.value.length && hostStore.IsHostEmpty) {
    message("权限不足,清先授权主机", "error", 2000);
    editableTabsValue.value = "";
    editableTabs.value = [];
    return;
  }

  // 仅适用于点击主机终端按钮跳转 不适用于点击web终端
  if (instanceID.value !== "" && fromOnlyID.value !== "") {
    webshellStore.setTermID(fromOnlyID.value);
    webshellStore.initTerm(instanceID.value);
    webshellStore.initSocket(instanceID.value);
  }
});

// 页面关闭时，销毁所有连接的 websocket 避免发生泄露
onDeactivated(() => {
  window.removeEventListener("resize", webshellStore.fitListener);
  webshellStore.closeAll();
});

// 主机组相关
const hostDefaultProps = ref({
  children: "children",
  label: "description",
});
</script>
<style scoped>
.web-terminal {
  display: flex;
  background-color: #060101;
  width: 100%;
  height: 100%;
  justify-content: left;
  /* justify-content: center; */
}
.luban-pre {
  color: #fff;
  display: flex;
  background-color: #060101;
  padding-top: 240px;
  padding-right: 10px;
  width: 100%;
  height: 100%;
  justify-content: center;
}
</style>
